package com.yanyeori.framework.datasource.switcher;

import com.yanyeori.framework.datasource.config.DynamicDataSource;
import com.yanyeori.framework.datasource.strategy.ListStrategy;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 读写分离，根据主数据源查找从数据源
 *
 * @author chenkuan 2021/8/19
 */
public class SlaveDBSwitcher {

    private static volatile SlaveDBSwitcher instance;

    private final Set<String> tempSalveMethodName = new HashSet<>();
    private final Set<String> tempNotSalveMethodName = new HashSet<>();

    private SlaveDBSwitcher() {
    }

    public static SlaveDBSwitcher getInstance() {
        if (instance == null) {
            synchronized (SlaveDBSwitcher.class) {
                if (instance == null) {
                    instance = new SlaveDBSwitcher();
                }
            }
        }
        return instance;
    }

    public String getSlaveDbByPrimary(String dbKey, Method method, List<String> slaveDbServicePrefix, ListStrategy listStrategy) {
        if (CollectionUtils.isEmpty(slaveDbServicePrefix)) {
            return dbKey;
        }
        String methodName = method.getName();
        if (tempNotSalveMethodName.contains(methodName)) {
            return dbKey;
        }
        //获取从库
        List<String> slaveDbs = DynamicDataSource.getInstance().getPrimarySlaveDbMap().get(dbKey);
        if (CollectionUtils.isEmpty(slaveDbs)) {
            return dbKey;
        }
        //判断方法名是否满足从库读写分离配置
        if (tempSalveMethodName.contains(methodName)) {
            return listStrategy.get(slaveDbs, dbKey);
        }
        for (String prefix : slaveDbServicePrefix) {
            if (methodName.startsWith(prefix)) {
                tempSalveMethodName.add(methodName);
                return listStrategy.get(slaveDbs, dbKey);
            }
        }
        tempNotSalveMethodName.add(methodName);
        return dbKey;
    }
}
